<?php
namespace app\controller\webhook;

use app\services\tools\WechatService;
use think\Controller;
use think\facade\Log;
use think\Request;

class Git extends Controller
{
    const BRANCH_MASTER = 'master';
    const BRANCH_DEVELOP = 'develop';
    const ENV_PRODUCTION = 'production';
    const ENV_TEST = 'test';
    const ENV_DEV = 'local';

    protected $openid;
    protected $config;

    public function initialize()
    {
        $this->config = config('wechat.default');
        $this->openid = config('wechat.to_openid');
    }

    public function push(Request $request)
    {
        if ($request->post('password') == config('services.git.gitee.password')) {
            $ref = $request->post('ref');
            $refArr = explode('/', $ref);
            $branch = end($refArr) ?? 'master';
            $env = config('app.app_env');
            if (
                ($branch == self::BRANCH_MASTER && $env == self::ENV_PRODUCTION) ||
                ($branch == self::BRANCH_DEVELOP && $env == self::ENV_TEST)
            ) {
                $path = config('services.webhook.path');
                if (is_win()) {
                    $command = "cd {$path} & git checkout {$branch} & git reset --hard & git pull origin {$branch}";
                } else {
                    $user = config('services.webhook.account');
                    $command = "cd {$path} && sudo -u {$user} git checkout {$branch} && sudo -u {$user} git reset --hard && sudo -u {$user} git pull origin {$branch} 2>/dev/null";
                }
                exec($command, $out, $status);
                $name = $request->post('sender.name', '');
                $res = $this->notify("{$name}将【{$env}】服务器代码更新了");
                return json($res);
            }
        }
    }

    protected function notify($text)
    {
        $wechat = WechatService::getInstance();
        return $wechat->sendText($this->openid, $text);
    }
}
